package ycl.gateway.exception;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;
import ycl.common.result.Result;
import ycl.common.result.REnum;

import java.util.HashMap;
import java.util.Map;

/**
 * 异常返回数据(弃用)
 * 代替: ycl.gateway.exception.ExceptionHandler
 *
 * @author ycl
 * @date 2022/9/23 0023 13:26:32
 */
@Slf4j
@Deprecated
public class JsonException extends DefaultErrorWebExceptionHandler {

	/**
	 * Create a new {@code DefaultErrorWebExceptionHandler} instance.
	 *
	 * @param errorAttributes    the error attributes
	 * @param resourceProperties the resources configuration properties
	 * @param errorProperties    the error configuration properties
	 * @param applicationContext the current application context
	 */
	@Deprecated
	public JsonException(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
		super(errorAttributes, resourceProperties, errorProperties, applicationContext);
	}


	@Override
	@Deprecated
	protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
		Throwable error = super.getError(request);
		log.error("{}", error.getMessage());
		error.printStackTrace();
		Result<Object> result;
		if (error instanceof NotFoundException)
			result = Result.fail(REnum.USED_NOT_FOUND);
		else
			result = Result.fail(REnum.USED_SERVER_ERROR);
		JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(result));
		return new HashMap<>(jsonObject);
	}

	@Override
	@Deprecated
	protected int getHttpStatus(Map<String, Object> errorAttributes) {
		return HttpStatus.OK.value();
	}

	@Override
	@SuppressWarnings("all")
	@Deprecated
	protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
		return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
	}

//	private Map<String, Object> writeResponse(String status, String message){
//		Result<Object> result = Result.fail(Integer.parseInt(status), message, null);
//		JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(result));
//		return JSONObjectConvertUtil.convert(result, Map.class);
//	}
}
